package ServerSide;
// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

import java.io.*;
import java.sql.SQLException;
import java.io.IOException;

import DBconnection.mysqlConnection;
import GUI.UserStudent;
//import File.CMyFile;

import ocsf.server.AbstractServer;
import ocsf.server.ConnectionToClient;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Vector;
import Common.*; 
import java.sql.ResultSetMetaData;

/**
 * This class overrides some of the methods in the abstract 
 * superclass in order to give more functionality to the server.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;re
 * @author Fran&ccedil;ois B&eacute;langer
 * @author Paul Holden
 * @version July 2000
 */
public class EchoServer extends AbstractServer 
{
  //Class variables *************************************************

	public   HashMap<String,Object> arg;
  /**
   * The default port to listen on.
   */
  final public static int DEFAULT_PORT = 5555;
  
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public EchoServer(int port) 
  {
    super(port);
  }

  
  //Instance methods ************************************************
  
  /**
   * This method handles any messages received from the client.
   *
   * @param msg The message received from the client.
   * @param client The connection from which the message originated.
 * @throws Exception 
   */
  public void handleMessageFromClient
    (Object msg, ConnectionToClient client)
  {     String[] FromUser;
  //String[] FromQuery=null;
  		//Object FromQuery;
ResultSet rs;
	int i;
	String[] result;//0-id,1-connection status,2-user type, 3-login status(ok\failed)
//	Courses c;
	int flag;
//	UserStudent userTask =new UserStudent();
	//Object CoursesResult=new Object();
	mysqlConnection DBcon = null;
try {
	DBcon = new mysqlConnection();
} catch (Exception e) {
	   System.out.println("Error in the db connection");
	e.printStackTrace();
}

FromUser = ((String)msg).split(" ");
//dealing with the option of submitting a task (saving on server) 
if (FromUser[0].equalsIgnoreCase("stusendtask"))	{
	//DBcon.submitAss(FromUser[1],FromUser[2],FromUser[3],FromUser[4]);
}	
//dealing with the teacher option of creating  a new task (saving on server) 
if (FromUser[0].equalsIgnoreCase("tnewtask"))	{
	DBcon.tnewtask(FromUser[1],FromUser[2],FromUser[3],FromUser[4],FromUser[5]);
}	
//dealing with the teacher option of Evaluation Form (saving on server) 
if (FromUser[0].equalsIgnoreCase("tNewevaluation"))	{
	 //DBcon.submitEvaluationForm(FromUser[1],FromUser[2],FromUser[3]);
}	

if(FromUser[0].equalsIgnoreCase("getEvaluationForm")){
	System.out.println("in IF OF getEvaluationForm");
	
}
//making the option of view new Assignment
if (FromUser[0].equalsIgnoreCase("viewNewAssignmentDetails")){
	arg = DBcon.viewNewAssignmentGetDetal((String)FromUser[1],(String)FromUser[2]);
	byte [] test = (byte[])arg.get("mybytearr");
	sendMsgToClient(client, arg);
}


//////////////////////////////////////////////////////////////////////////////////////////	
if(FromUser[0].equalsIgnoreCase("login"))
{
   System.out.println("\n  in login");
   result=DBcon.login(FromUser);
	
	if (result[3].equalsIgnoreCase("FAILED")) 
		{System.out.println("\n  from server: login failed!");
	sendMsgToClient(client,result );}
else{ System.out.println("\n from server: login O.K");
	sendMsgToClient(client,result );}
}
if(FromUser[0].equalsIgnoreCase("logout"))
{
 
   DBcon.logout(FromUser);
   System.out.println("\n  from server: user loged out ok");
	sendMsgToClient(client,"\n  from server: user loged out ok" );

} 

if(FromUser[0].equalsIgnoreCase("getYears"))
{
   result=DBcon.YearQuery(FromUser);
   System.out.println("\n"+ result[0]+result[1]+result[2]);
   sendMsgToClient(client,result );
   
}
if(FromUser[0].equalsIgnoreCase("StudentCoursesQuery"))
{
 Object CoursesResult=DBcon.CourseToStudentQuery(FromUser);
 

 Vector res = (Vector)CoursesResult;
 sendMsgToClient(client, res);
 System.out.println("\n return from CourseToStudentQuery  ");
   		
   		
		
}
if(FromUser[0].equalsIgnoreCase("ChildQuery"))
{
   Object ChildResult=DBcon.ChildQuery(FromUser);
	Vector res = (Vector)ChildResult;
	sendMsgToClient(client, res);
	 System.out.println("\n return from ChildQuery  ");
	 Vector<String[]> tempResult=(Vector<String[]>)ChildResult;
	 String[] temp=new String[2];
	 temp[0]="ForParent";
	 for( i=1;i<(tempResult.size()-1);i++)
	 {
		 String[] array = (String[])tempResult.get(i);
		 temp[1]=array[0];
		 Object CoursesResult=DBcon.CourseToStudentQuery(temp);
		 System.out.println("\n tempresult "+ array[0]);
		 res = (Vector)CoursesResult;
		 sendMsgToClient(client, res);
		 }
	/* temp[0]="PersonalDataForParent";
	 for( i=1;i<(tempResult.size()-1);i++)
	 {
		 String[] array = (String[])tempResult.get(i);
		 temp[1]=array[0];
		 Object PData=DBcon.PersonalDataQuery(temp);
		 System.out.println("\n tempresult "+ array[0]);
		 res = (Vector)PData;
		 sendMsgToClient(client, res);
		 }*/
	
}
if(FromUser[0].equalsIgnoreCase("StudentsQuery"))
{
   Object IdsResult=DBcon.IdsForPrinciple();
   Vector<String[]> tempResult=(Vector<String[]>)IdsResult;
   String[] temp=new String[2];
   temp[0]="ForPrinciple";
   for( i=1;i<(tempResult.size()-1);i++)
	 {
		 String[] array = (String[])tempResult.get(i);
		 temp[1]=array[0];
		 Object CoursesResult=DBcon.CourseToStudentQuery(temp);
		 System.out.println("\n tempresult "+ array[0]);
		 Vector res = (Vector)CoursesResult;
		 sendMsgToClient(client, res);
		 }
   sendMsgToClient(client, true);
   
   
}
if(FromUser[0].equalsIgnoreCase("PersonalDataForStudent"))
{
   Object PData=DBcon.PersonalDataQuery(FromUser);
   Vector res = (Vector)PData;
   sendMsgToClient(client, res);
}
if(FromUser[0].equalsIgnoreCase("PersonalDataForParent"))
{
   Object PData=DBcon.PersonalDataQuery(FromUser);
   Vector res = (Vector)PData;
   sendMsgToClient(client, res);
}
if(FromUser[0].equalsIgnoreCase("PersonalDataForPrinciple"))
{
   Object PData=DBcon.PersonalDataQuery(FromUser);
   Vector res = (Vector)PData;
   sendMsgToClient(client, res);
}
if(FromUser[0].equalsIgnoreCase("ClassesQuery"))
{
   Object Classes=DBcon.ClassesQuery();
   Vector res = (Vector)Classes;
   sendMsgToClient(client, res);
}
if(FromUser[0].equalsIgnoreCase("StudUnatQuery"))
{
   Object Students=DBcon.UnattributedStudQuery();
   Vector res = (Vector)Students;
   sendMsgToClient(client, res); 
}
if(FromUser[0].equalsIgnoreCase("CoursesAdminQuery"))
{
   Object Courses=DBcon.CoursesToAdmin();
   Vector res=(Vector)Courses;
   sendMsgToClient(client, res); 
   
}
if(FromUser[0].equalsIgnoreCase("TeachersQuery"))
{
   Object Teachers=DBcon.TeachersQuery();
   Vector res = (Vector)Teachers;
   sendMsgToClient(client, res); 
}
if(FromUser[0].equalsIgnoreCase("StudentQueryForEx"))
{
   Object Students=DBcon.StudentsExQuery();
   Vector res = (Vector)Students;
   sendMsgToClient(client, res);
  
  // sendMsgToClient(client, true);
}

if(FromUser[0].equalsIgnoreCase("StudentCoursesRemoveExQuery"))
{
  Object Courses=DBcon.StudentCoursesRemoveExQuery(); 
  Vector res = (Vector)Courses;
  sendMsgToClient(client, res); 
  
}
if(FromUser[0].equalsIgnoreCase("StudentCoursesAddExQuery"))
{
  Object Courses=DBcon.StudentCoursesAddExQuery(); 
  Vector res = (Vector)Courses;
  sendMsgToClient(client, res); 
  
}
if(FromUser[0].equalsIgnoreCase("CoursesOfClassesAdminQuery"))
{
  Object CoursesOfClasses=DBcon.CoursesOfClassesToAdmin(); 
  Vector res = (Vector)CoursesOfClasses;
  sendMsgToClient(client, res); 
  
}
if(FromUser[0].equalsIgnoreCase("ParentQueryForManagment"))
{
  Object Parents=DBcon.ParentQueryForManagment(FromUser); 
  Vector res = (Vector)Parents;
  sendMsgToClient(client, res); 
  
}
if(FromUser[0].equalsIgnoreCase("CoursesOfStudOfClassQuery"))
{
  Object CourseOfStud=DBcon.CoursesOfStudOfClassQuery();
  Vector res = (Vector)CourseOfStud;
  sendMsgToClient(client, res); 
  
}

if(FromUser[0].equalsIgnoreCase("CoursesWithPreCoursesQuery"))
{
  Object Courses=DBcon.PreCoursesQuery();
  Vector res = (Vector)Courses;
  sendMsgToClient(client, res); 
  
}

if(FromUser[0].equalsIgnoreCase("StudentwithClassQuery"))
{
  Object StudentWithClasses=DBcon.StudentsExQuery();
  Vector<String[]> tempResult=(Vector<String[]>)StudentWithClasses;
 
  String[] array= tempResult.remove(tempResult.size()-1);
  array[0]="StudentwithClassQuery";
  tempResult.add(array);
  Vector res = (Vector)tempResult;
  sendMsgToClient(client, res);
}
if(FromUser[0].equalsIgnoreCase("AttributeStudentsToCourse"))
{
	Object Approval=DBcon.UpdateCourseToStudent(FromUser);
	Vector res=(Vector)Approval;
	sendMsgToClient(client, res);
	}
if(FromUser[0].equalsIgnoreCase("UpdateLockToCurrentSemester"))
{	Object Approval=DBcon.UpdateLockToCurrentSemester();
	Vector res=(Vector)Approval;
	sendMsgToClient(client, res);
	
	}
if(FromUser[0].equalsIgnoreCase("CreateExReqRemoveStudFromCourse"))
{	Object Approval=DBcon.CreateExReqRemoveStudFromCourse(FromUser);
	Vector res=(Vector)Approval;
	sendMsgToClient(client, res);
	
	}
	if(FromUser[0].equalsIgnoreCase("CreateExReqAddStudToCourse"))
	{	Object Approval=DBcon.CreateExReqAddStudToCourse(FromUser);
		Vector res=(Vector)Approval;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("DataForHistBetweenTeachersInChosenClass"))
	{	Object BTeachForClass=DBcon.DataForHistBetweenTeachersInChosenClass(FromUser);
		Vector res=(Vector)BTeachForClass;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("DataForHistBetweenCoursesToChosenClass"))
	{	Object BCoursesForClass=DBcon.DataForHistBetweenCoursesToChosenClass(FromUser);
		Vector res=(Vector)BCoursesForClass;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("DataForHistBetweenClassesToChosenTeacher"))
	{	Object BClasesForTeacher=DBcon.DataForHistBetweenClassesToChosenTeacher(FromUser);
		Vector res=(Vector)BClasesForTeacher;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("CreateExReqTeacherReplacement"))
	{	Object Approval=DBcon.CreateExReqTeacherReplacement(FromUser);
		Vector res=(Vector)Approval;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("CoursesOfClassQuery"))
	{	Object CoursesOfClass=DBcon.CoursesOfClassQuery();
		Vector res=(Vector)CoursesOfClass;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("InsertStudentToClass"))
	{	Object Approval=DBcon.InsertStudentToClass(FromUser);
		Vector res=(Vector)Approval;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("SetDesExReqAddStudToCourse"))
	{	Object Des=DBcon.SetDesExReqAddStudToCourse(FromUser);
		Vector res=(Vector)Des;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("SetDesExReqRemovalStudToCourse"))
	{	Object Des=DBcon.SetDesExReqRemovalStudToCourse(FromUser);
		Vector res=(Vector)Des;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("SetDesExReqReplaceTeacher"))
	{	Object Des=DBcon.SetDesExReqReplaceTeacher(FromUser);
		Vector res=(Vector)Des;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("ExReqTeacherRepQuery"))
	{	Object Requests=DBcon.ExReqTeacherRepQuery();
		Vector res=(Vector)Requests;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("ExReqStudAddQuery"))
	{	Object Requests=DBcon.ExReqStudAddQuery();
		Vector res=(Vector)Requests;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("ExReqStudRemQuery"))
	{	Object Requests=DBcon.ExReqStudRemQuery();
		Vector res=(Vector)Requests;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("CoursesAdminForExQuery"))
	{	Object Requests=DBcon.CoursesAdminForExQuery();
		Vector res=(Vector)Requests;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("TeachersForHistQuery"))
	{	Object Teachers=DBcon.TeachersForHistQuery();
		Vector res=(Vector)Teachers;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("CreateNewClass"))
	{	Object Approval=DBcon.CreateNewClass(FromUser);
		Vector res=(Vector)Approval;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("CreateNewSemester"))
	{	Object Approval=DBcon.CreateNewSemester();
		Vector res=(Vector)Approval;
		sendMsgToClient(client, res);
	}
	if(FromUser[0].equalsIgnoreCase("ParentBlockForManagment"))
	{	Object Approval=DBcon.ParentBlockForManagment(FromUser);
		Vector res=(Vector)Approval;
		sendMsgToClient(client, res);
	}
	
  }
//}
//	try {
//	Object res=DBcon.Uquery(FromUser);
//	Vector resu = (Vector)res;
//	sendMsgToClient(client , resu);
	
//	} catch (SQLException e) {
	// TODO Auto-generated catch block
//	e.printStackTrace();
//	}



//   System.out.println("UserName"+FromQuery[0]+ "Password" +FromQuery[1] + "Is connected" + FromQuery[2]);
//end of dani
// this.sendToAllClients(msg);

public void sendMsgToClient(ConnectionToClient client, Object msg){
try{
	client.sendToClient(msg);
	System.out.println("\n send to client ok  ");
	
}
catch (IOException ex) {
	ex.printStackTrace();
}
} 
/**
* This method overrides the one in the superclass.  Called
* when the server starts listening for connections.
*/
protected void serverStarted()
{
System.out.println
("Server listening for connections on port " + getPort());
}

/**
* This method overrides the one in the superclass.  Called
* when the server stops listening for connections.
*/
protected void serverStopped()
{
System.out.println
("Server has stopped listening for connections.");
}
  
//Class methods ***************************************************

/**
* This method is responsible for the creation of 
* the server instance (there is no UI in this phase).
*
* @param args[0] The port number to listen on.  Defaults to 5555 
*          if no argument is entered.
*/
	public static void main(String[] args) 
	{
	int port = 0; //Port to listen on
	
		try
		{
			port = Integer.parseInt(args[0]); //Get port from command line
		}
		catch(Throwable t)
		{
			port = DEFAULT_PORT; //Set port to 5555
		}
		
		EchoServer sv = new EchoServer(port);
		
		try 
		{
			sv.listen(); //Start listening for connections
		} 
		catch (Exception ex) 
		{
			System.out.println("ERROR - Could not listen for clients!");
		}
	}
}
//End of EchoServer class
